package mall.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import mall.bean.Product;
import mall.service.ProductService;
import mall.service.impl.ProductServiceImpl;

@WebServlet("/product/list")
public class ProductListServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private ProductService productService = new ProductServiceImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 请求参数默认值
		int pageSize = 8;
		int pageNo = 1;
		// 获取前端传递的参数
		String pageSizeString = req.getParameter("pageSize");
		String pageNoString = req.getParameter("pageNo");
		if (pageSizeString != null)
			pageSize = Integer.parseInt(pageSizeString);
		if (pageNoString != null)
			pageNo = Integer.parseInt(pageNoString);
		// 调用service去查询总行数
		long totalRows = productService.count();
		// 计算总页数
		long totalPages = totalRows / pageSize;
		if (totalRows % pageSize > 0) {
			totalPages += 1;
		}
		// 调用service层的方法 得到数据集合
		List<Product> list = productService.findListPage(pageNo, pageSize);
		// 把这些需要返回到前端的数据包装成一个map
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("totalRows", totalRows);
		map.put("pageSize", pageSize);
		map.put("pageNo", pageNo);
		map.put("totalPages", totalPages);
		map.put("list", list);
		// 把map转换为json格式
		String json = JSON.toJSONString(map, true);
		// 返回json到前端
		resp.setContentType("application/json;charset=UTF-8");
		PrintWriter writer = resp.getWriter();
		writer.write(json);
		writer.flush();
		writer.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}
}
